﻿
Imports System.Threading

Public Class rcpointer(Of T)
    Inherits pointer(Of T)

    Private ReadOnly unalloc As void(Of T) = Nothing
    Private refcount As Int32 = 0

    Public Sub New(ByVal unalloc As void(Of T))
        Me.unalloc = unalloc
    End Sub

    Public Sub New()
        Me.New(Nothing)
    End Sub

    Protected Overridable Sub [erase]()
        If Not unalloc Is Nothing Then
            unalloc([get]())
        End If
        clear()
    End Sub

    Private Function e() As Boolean
        [erase]()
        Return True
    End Function

    Public Function inc_ref() As Int32
        Return Interlocked.Increment(refcount)
    End Function

    Public Function dec_ref() As Boolean
        assert(refcount > 0)
        Return Interlocked.Decrement(refcount) = 0 AndAlso e()
    End Function
End Class
